import http from './http'

export async function fetchLeaderboard(params = {}) {
  try {
    const query = new URLSearchParams()
    if (params.type) query.set('type', params.type)
    if (params.top) query.set('top', params.top)
    const url = query.toString() ? `/api/leaderboard?${query.toString()}` : '/api/leaderboard'
    const res = await http.get(url)
    return res.data || []
  } catch (error) {
    console.error('Failed to fetch leaderboard:', error)
    return []
  }
}

export async function fetchUserRank(userId) {
  try {
    const res = await http.get('/api/leaderboard')
    const leaderboard = res.data || []
    const userRank = leaderboard.find(player => player.userId === userId)
    return userRank ? userRank.rank : null
  } catch (error) {
    console.error('Failed to fetch user rank:', error)
    return null
  }
}
